<?php

defined('_SECURITY_TOKEN') or die("caia fora");

abstract class model{
	
	
	public function __construct(){
		

	}
	
	
	public function save( $table="", $args=array(), $PK='id' ){
		
		$result	=	false;
		$db		=	application::getDbMysql();
		
		
		if( empty( $args[$PK]) ){
			
			$columns="";
			$values="";
			
			foreach( $args as $key=>$item ){
	
				
				if($columns=='')
					$columns.=$item->Field;
				else 
					$columns.=','.$item->Field;
				
				$valor="";
				
				if( strpos (' '.$item->Type, 'varchar') ){
					//varchar
					$valor='"'.$item->Value.'"';
				}elseif( strpos (' '.$item->Type, 'datetime') ){
					$valor='"'.$item->Value.'"';					
				}elseif( strpos (' '.$item->Type, 'int') ){
					$valor=''.$item->Value.'';					
				}else{
					$valor=''.$item->Value.'';					
				}
				
								
				if($values=='')
					$values.=$valor;
				else 
					$values.=','.$valor;
				
			}
			
						
			$query	=	"INSERT INTO "
						.$table
						.'('
						.$columns
						.') VALUES ('
						.$values
						.')';
		
			$result	=	$db->setQuery( $query );

			
		}else{
			
			$query	=	"SELECT * FROM "
					.$table
					."WHERE id="
					.$args['id']
					." LIMIT 0,1";
		
			$rows	=	$db->getQuery( $query );
			
			if( count($rows) ){
				
				var_dump( $rows );
				
			}
			
			
		}
				
		return $result;
	
	}
	
	
	public function bind( $table="", $args=array() ){
		
		$columns=	array();
		$result	=	array();
		$db		=	application::getDbMysql();
		
				
		$query	=	"SHOW COLUMNS FROM "
					.$table
					." ";
		
		$rows	=	$db->getQuery( $query );
		
		if( count($rows) ){
			
			foreach( $rows as $key=>$item){
				$columns[]	=	(object) array( 'Field'=>$item->Field, 'Type'=>$item->Type );
			}
			
		}
		
		foreach( $columns as $key=>$item ){

			if( array_key_exists($item->Field, $args))
				// /$result[$item->Field]= $args[$item->Field];
				$result[]	=	(object) array( 'Field'=>$item->Field, 'Type'=>$item->Type, 'Value'=>$args[$item->Field] );
			
		}
		
		return $result;		
	}
	
	
	public function getItem( $table="", $filter=array(), $limit="" ){
		
		$result	=	"";
		$db		=	application::getDbMysql();

		$where	=	$this->splitWhere( $filter );		
				
		$query	=	"SELECT * FROM "
					.$table
					." "
					.$where
					." "
					.$limit;
		
		$rows	=	$db->getQuery( $query );

		if( count($rows) ){
			
			//if( $rows[0]->email == $email 
				//&& $rows[0]->password == $password){
					
					$result=$rows;
				//}
			
		}
		
		
		return $result;
	}
	
	
	
	public function splitWhere( $where )
	{
		
		return ( count( $where ) ? 
								' WHERE ' . implode( ' AND ', $where ) : 
								'' );
	}
	
	
	
}

?>